package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.CardSet;
//import model.Dealer;
import model.Game;
import model.Player;
import model.RankCardSet;
//import model.Card;

/**
 * Servlet implementation class RankHandServlet
 */
@WebServlet(name = "RankHandsServlet", urlPatterns = { "/rankHands" })
public class RankHandsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public RankHandsServlet() {
        super();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		RankCardSet rankCardSet = (RankCardSet) getServletContext().getAttribute("rankCardSet");
		Player players[] = (Player[]) getServletContext().getAttribute("playerList");
		Game game = (Game) getServletContext().getAttribute("game");
		ArrayList<model.Card> tableCards = game.getRound().getCardList();
		ArrayList<Player> playerList = new ArrayList<Player>();
		CardSet cardSet = null;
		game.getRound().setHasEnded(true);
		game.getRound().setShowDown(false);
		
		for(int i=0; i<players.length; i++) {
			if (players[i]!=null) {
				players[i].setBet(0);
				if(!players[i].hasFolded())
					playerList.add(players[i]);
			}
		}
		for(Player player : playerList) {
			cardSet = new CardSet(player);
			cardSet.addToCardSet(player.getHand().getCardList(), tableCards);
			rankCardSet.addCardSet(cardSet);
		}
		
		//Rank Hands
		rankCardSet.rankCheck();
		
		//Count How Many Winners
		int countWinners = 0;
		for(CardSet playerCardSet : rankCardSet.getCardSets()) {
			if(playerCardSet.isWinner())
				countWinners++;
		}
		
		int potMoney = 0;
		potMoney = game.getRound().getPot().getAmount();
		potMoney = potMoney/countWinners;
		game.getRound().getPot().setAmount(0);
		
		for(CardSet playerCardSet : rankCardSet.getCardSets()) {
			if(playerCardSet.isWinner())
				playerCardSet.getPlayer().setMoney(playerCardSet.getPlayer().getMoney() + potMoney);
		}
		
		//Debug
		String output = new String();
		for(CardSet playerCardSet : rankCardSet.getCardSets()) {
			if(playerCardSet.isWinner())
				output += playerCardSet.getPlayer().getName() + " WINS with a " + playerCardSet.getRanking() + "<br />";
		}
		
		System.out.println(output);
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println(output);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
